﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using System.Web.Http.Filters;
using Newtonsoft.Json.Linq;
using ProjectBase.Core;

using $prjsn$.Entity;
using $prjsn$.Common.Business;

namespace $safeprojectname$
{
    public class ListFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)
        {
            object obj;
            if(context.ControllerContext.Request.Properties.TryGetValue("ODataServiceMessage", out obj))
            {
                var message = obj as ServiceMessage;
                if (message.Is() && message.Messages.IsNotEmpty())
                {
                    context.Response = context.Request.CreateResponse<ServiceMessage>(HttpStatusCode.BadRequest, message);
                }
            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            var filter = context.ActionContext.ActionArguments.First().Value as IFilter<int>;
            if (filter.IsNull())
            {
                return;
            }

            var objectContent = context.Response.Content as ObjectContent;
            if (objectContent.IsNull())
            {
                return;
            }

            var list = objectContent.Value as IEnumerable<object>;
            if (list.IsNull())
            {
                return;
            }

            // wrap the result with the OData v2 style 
            //{
            //  "d": {
            //    "results": [
            //      {
            //        ...
            //      }
            //    ],
            //    "__count": 100
            //  }
            //}
            int? inlineCount = filter.ShowInlineCount ? filter.TotalRows : default(int?);

            var odataMessage = new ODataMessage(inlineCount, list, filter.TakeRows, filter.SkipRows);
            var content = new ObjectContent(typeof (ODataMessage), odataMessage, objectContent.Formatter);
            context.Response.Content = content;
        }
    }
}
